<template>
  <div data-v-whisper123 class="whisper">
    <div class="top-box"><NewTopNav></NewTopNav></div>
    <div class="body-box">
      <div class="center-box">
        <el-tabs
          class="whisper-tabs"
          v-model="activeUser"
          closable
          @tab-remove="removeTab"
          @tab-click="switchUser"
        >
          <el-tab-pane
            v-for="item in userList"
            :key="item.name"
            :name="item.name"
            class="whisper-tab-pane"
          >
            <div class="user-list" slot="label">
              <img :src="item.pic" alt="" />
              <span>
                {{ item.username }}
              </span>
            </div>

            <div class="whisper-content">
              <div class="whisper-info">
                <section
                  v-for="listitem in chatMessageList"
                  :key="listitem.id"
                  class="whisper-info-list"
                  :class="[
                    listitem.receiver == activeUser ? 'whisper-right' : '',
                  ]"
                >
                  <div class="whisper-info-list-tx">
                    <img :src="listitem.sender_pic" alt="" />
                  </div>
                  <div class="whisper-info-list-content">
                    <p>
                      {{ listitem.msg }}
                    </p>
                  </div>
                </section>
              </div>
              <div class="whisper-input">
                <div class="whisper-input-top"></div>
                <el-input
                  type="textarea"
                  placeholder="请输入内容"
                  v-model="textarea"
                  maxlength="300"
                  resize="none"
                  show-word-limit
                >
                </el-input>
                <div class="whisper-input-bottom">
                  <span @click="sendMsg(item)">发送</span>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script>
import NewTopNav from "@/components/NewTopNav";

export default {
  name: "Whisper",
  components: {
    NewTopNav,
  },

  data: function () {
    return {
      activeUser: this.$route.params.id,

      userList: [],
      chatMessageList: [],

      userId: "",
      currentUserPic: "",

      textarea: "",

      len: 0,
    };
  },

  created() {
    this.connect();

    this.$getuserinfo((data) => {
      this.userId = data.id;
      this.currentUserPic = data.user_pic;
      // console.log(data);
    });
  },

  mounted() {
    // 1、获取私聊过的对象列表
    this.getWhisperUser();
    // 2、获取私聊对象的信息和私聊记录
    this.getPrivateChat();
  },

  methods: {
    // 切换私聊的用户
    switchUser(tag) {
      this.textarea = "";
      this.$router.push(`/whisper/${tag.$options.propsData.name}`);

      this.getPrivateChat();
    },

    // 发送私信
    sendMsg(item) {
      console.log(item);

      if (!this.textarea) {
        return this.$message({
          message: "不能意念发送啊",
          type: "warning",
        });
      }
      // console.log(typeof this.userId.toString(), typeof this.$route.params.id);
      // console.log(this.userId.toString() === this.$route.params.id);

      if (this.userId.toString() === this.$route.params.id) {
        return this.$message({
          message: "不能给自己发送信息！",
          type: "warning",
        });
      }

      // 获取发送信息
      this.len++;
      let id = this.len;
      let sender = this.userId.toString();
      let sender_pic = this.currentUserPic;
      let receiver = this.$route.params.id;
      let receiver_pic = "";
      let msg = this.textarea;

      this.textarea = "";

      // if (item.receiver == this.$route.params.id) {
      //   sender_pic = item.sender_pic;
      //   receiver_pic = item.receiver_pic;
      // } else {
      //   sender_pic = item.receiver_pic;
      //   receiver_pic = item.sender_pic;
      // }

      // 发送私信
      this.$socket.emit(
        "privateChat",
        {
          id,
          sender,
          sender_pic,
          receiver,
          receiver_pic,
          msg,
        },
        (data) => {
          // console.log(data);
          // 将本次私信保存到数据库中
          this.axios
            .post(`setPrivateChat`, {
              id,
              sender,
              sender_pic,
              receiver,
              receiver_pic,
              msg,
            })
            .then((response) => {
              if (response.data.status == 200) {
                // console.log(response);
                this.getPrivateChat();
              } else {
                console.log(response);
              }
            })
            .catch((err) => {
              console.log(err);
            });
        }
      );
    },

    // 判断当前要私聊的对象是否已在现有的私聊过的列表中，没有则在前面插入
    addTab() {
      this.textarea = "";

      let isHad = false;

      for (let i = 0; i < this.userList.length; i++) {
        if (this.userList[i].name == this.$route.params.id) {
          isHad = true;
        }
      }

      if (!isHad) {
        // 获取该用户的信息
        let name = this.$route.params.id + "";
        let pic = "";
        let username = "";

        this.axios
          .get(`getuser/${name}`)
          .then((response) => {
            if (response.data.status == 200) {
              // console.log(response.data);

              if (response.data.data) {
                pic = response.data.data.user_pic;
                username = response.data.data.username;

                this.userList.unshift({
                  name,
                  pic,
                  username,
                });
              } else {
                this.$message({
                  message: "用户不存在",
                  type: "error",
                });
              }
            } else {
              console.log(response);
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },

    removeTab(targetName) {
      console.log(targetName);
    },

    // 获取私聊过的对象列表
    getWhisperUser() {
      this.axios
        .get(`getWhisperUser`)
        .then((response) => {
          if (response.data.status == 200) {
            // console.log(response);
            // this.userList.push(...response.data.data);
            this.userList = response.data.data;

            if (!this.$route.params.id) {
              this.$router.push(`/whisper/${this.userList[0].name}`);
              this.activeUser = this.userList[0].name;
              this.getPrivateChat();
            } else {
              this.addTab();
            }
          } else {
            console.log(response);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 获取私信记录
    getPrivateChat() {
      let receiverId = this.$route.params.id;

      this.axios
        .get(`getPrivateChat/${receiverId}`)
        .then((response) => {
          if (response.data.status == 200) {
            // console.log(response);
            this.chatMessageList = response.data.data;
            // this.chatMessageList = response.data.data;
            // console.log(this.chatMessageList);
          } else {
            console.log(response);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 连接 socket
    connect() {
      // 订阅事件
      this.sockets.subscribe("updateChatMessageList", (data) => {
        // console.log("updateChatMessageList ", data);
        // 这里不能直接 通过 this.getPrivateChat() 获取私信记录，有 bug：执行完 getPrivateChat后数据改变，但DOM不改变，采用在前端直接添加一个‘假’的新消息
        this.chatMessageList.push(data);
      });
    },
  },

  sockets: {
    //客户端接收后台传输的socket事件
    updateChatMessageList: function (data) {
      // console.log(data);
    },
  },

  // beforeDestroy() {
  //   this.$socket.close();
  // },
};
</script>

<style lang="scss">
.whisper[data-v-whisper123] {
  .whisper-tabs {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    // background-color: rgba(255, 255, 255, 0.822);
    border-radius: 8px;

    .el-tabs__header {
      width: 100%;
      height: 60px;

      .el-tabs__nav-wrap {
        width: 100%;
        height: 100%;

        .el-tabs__nav-scroll {
          width: 100%;
          height: 100%;

          .el-tabs__nav {
            display: flex;
            width: 100%;
            height: 100%;

            .el-tabs__item {
              display: flex;
              height: 60px;
              line-height: 60px;

              .user-list {
                display: flex;
                align-items: center;

                img {
                  display: inline-block;
                  width: 50px;
                  height: 50px;
                  border-radius: 50%;
                  object-fit: cover;
                }

                span {
                  margin-left: 10px;
                }
              }

              .el-icon-close {
                display: flex;
                align-items: center;
              }
            }
          }
        }
      }
    }

    .el-tabs__content {
      width: 100%;
      flex-grow: 1;

      .whisper-tab-pane {
        width: 100%;
        height: 100%;

        .whisper-content {
          display: flex;
          flex-direction: column;
          width: 100%;
          height: 100%;

          ::-webkit-scrollbar-corner {
            display: none;
          }

          .whisper-info::-webkit-scrollbar {
            display: block;
            width: 8px;
            height: 8px;
          }

          .whisper-info::-webkit-scrollbar-thumb {
            background: rgb(87, 87, 87);
            border-radius: 4px;
          }

          .whisper-info {
            width: 100%;
            flex-grow: 1;

            overflow-x: hidden;
            overflow-y: scroll;

            .whisper-left {
              flex-direction: row;
            }

            .whisper-right {
              flex-direction: row-reverse;
            }

            .whisper-info-list {
              display: flex;
              width: 100%;
              padding: 10px 0;

              .whisper-info-list-tx {
                width: 60px;
                margin: 0 15px;

                img {
                  width: 60px;
                  height: 60px;
                  border-radius: 10px;
                }
              }

              .whisper-info-list-content {
                max-width: 70%;

                p {
                  padding: 10px 20px;
                  font-size: 16px;
                  background-color: #fff;
                  border-radius: 8px;
                }
              }
            }
          }

          .whisper-input {
            display: flex;
            flex-direction: column;
            width: 100%;
            height: 160px;
            background-color: rgba(0, 0, 0, 0.3);
            border-radius: 8px;

            .whisper-input-top {
              width: 100%;
              height: 40px;
            }

            .el-textarea {
              width: 100%;
              flex-grow: 1;
              font-size: 18px;

              .el-textarea__inner {
                width: 100%;
                height: 100%;
                color: #fff;
                background-color: transparent;
                border: none;
              }

              .el-input__count {
                bottom: -27px;
                right: 94px;
                font-size: 14px;
                color: #fff;
                background-color: transparent;
              }
            }

            .whisper-input-bottom {
              display: flex;
              flex-direction: row-reverse;
              align-items: center;
              width: 100%;
              height: 35px;

              span {
                padding: 3px 18px;
                margin-right: 18px;
                font-size: 14px;
                color: #fff;
                background-color: rgba(0, 0, 0, 0.3);
                border-radius: 5px;
                cursor: pointer;
              }
            }
          }
        }
      }
    }
  }
}
</style>

<style lang="scss" scoped>
.whisper[data-v-whisper123] {
  width: 100%;
  height: 100%;

  .top-box {
    width: 100%;
    height: 7%;
    background-color: #fff;
    border-bottom: 1px solid #eee;
    box-shadow: 0 0 6px #eee;
  }

  .body-box {
    width: 100%;
    height: 93%;

    background-image: url("../../assets/img/whisper1.jpg");
    background-size: 100% 100%;
    background-repeat: no-repeat;
    background-position: center;

    .center-box {
      //   display: flex;
      //   flex-direction: column;
      width: 70%;
      height: 100%;
      margin: 0 auto;
      padding: 10px 18px;
      background-color: rgba($color: #000000, $alpha: 0.3);
    }
  }
}
</style>